import axios from 'axios';


const API_KEY = 'sk-da55973307704d9cb87053fd13249883'; // 替换为实际 Key
const API_URL = 'https://api.deepseek.com/v1/chat/completions';
export const askDeepSeek = async (messages) => {
	try {
		const response = await axios.post(
			API_URL, {
				model: "deepseek-chat",
				messages: messages, // 使用传入的消息数组
			}, {
				headers: {
					Authorization: `Bearer ${API_KEY}`,
					"Content-Type": "application/json",
				},
			}
		);
		return response.data.choices[0].message.content;
	} catch (error) {
		console.error("API 请求失败:", error);
		return "请求出错，请重试";
	}
};

const key_dify = "app-RDTja9MeZ2Jh3fFS9TJLIa0t";
const url_dify = "http://192.168.0.90/v1/chat-messages"
export const askDify = async (messages) => {
	try {
		const response = await axios.post(
			url_dify, messages, {
				headers: {
					Authorization: `Bearer ${key_dify}`,
					"Content-Type": "application/json",
				},
			}
		);
		return response.data;
	} catch (error) {
		console.error("API 请求失败:", error);
		return {
			error: "error",
			answer: '请求出错，请稍后重试'
		};
	}
};
export const askDifySteam = async (requestData) => {
	console.log(requestData)
	let requestTask = uni.request({
		url: url_dify,
		method: 'POST',
		header: {
			'Content-Type': 'application/json',
			'Authorization': `Bearer ${key_dify}`,
		},
		data: requestData,
		enableChunked: true, // 启用分块传输‌:ml-citation{ref="2,3" data="citationList"}
		responseType: 'arraybuffer', // 必须设置为二进制流
		success(res) {
			console.log(res.data);
			console.log("连接建立");
			const textChunk = new TextDecoder('utf-8').decode(res.data);
			console.log(textChunk)
		}
	});
	// 分片模式，仅支持微信小程序
	let buffer = '';
	requestTask.onChunkReceived((chunk) => {
		const textChunk = new TextDecoder('utf-8').decode(chunk.data);
		console.log(textChunk)
		buffer += textChunk;
		// 按SSE协议解析数据块（Dify默认使用SSE格式）
		while (buffer.includes('\n\n')) {
			const rawMsg = buffer.substring(0, buffer.indexOf('\n\n'));
			buffer = buffer.substring(buffer.indexOf('\n\n') + 2);
			if (rawMsg.startsWith('data:')) {
				const payload = JSON.parse(rawMsg.replace('data:', '').trim());
				console.log("流式返回值:", payload
					.answer); // 实际数据在answer字段‌:ml-citation{ref="1,3" data="citationList"}
			}
		}
	});
}